import Mock from 'mockjs'
import { getQuery } from "@/mock/common/util";

const data = Mock.mock({
  "list|10": [
    {
      "id": '@increment(1)',
      "title": "@ctitle",
      "content": "@cparagraph",
      "add_time": "@date(yyyy-MM-dd hh:mm:ss)"
    }
  ]
})

export default {
  // 删除
  'post|/api/delete/news':  options => {
    let body = JSON.parse(options.body)
    const index = data.list.findIndex(item => item.id === body.id)
    data.list.splice(index, 1)
    return {
      status: 200,
      message: '删除成功',
      list: data.list
    }
  },
  // 添加
  'post|/api/add/news': options => {
    let body = JSON.parse(options.body)
    data.list.push(Mock.mock({
      "id": '@increment(1)',
      "title": body.title,
      "content": body.content,
      "add_time": "@date(yyyy-MM-dd hh:mm:ss)"
    }))
    return {
      status: 200,
      message: '添加成功',
      list: data.list
    }
  },
  'get|/api/get/news': options => {
    // 获取传递的参数pageindex
    const pagenum = getQuery(options.url,'pagenum')
        
    // 获取传递的参数pagesize
    const pagesize = getQuery(options.url,'pagesize')
    // 截取数据的起始位置
    const start = (pagenum-1)*pagesize
    // 截取数据的终点位置
    const end = pagenum*pagesize
    // 计算总页数
    const totalPage = Math.ceil(data.list.length/pagesize)
    // console.log('mock_test', data.list.length, totalPage, pagenum, pagesize, start, end)
    // 数据的起始位置：(pageindex-1)*pagesize  数据的结束位置：pageindex*pagesize
    const list = pagenum>totalPage?[]:data.list.slice(start,end)

    return {
      status: 200,
      message: '获取新闻列表成功',
      list: list,
      total: data.list.length
    }
  },
}

